<template>
  <div class="view-fill">
    <div v-if="!adjustPriceModifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="'调价单详情'"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRecall" @click="recall">撤回</el-button>
          <el-button v-if="canApprove" @click="btnFlow('approve')"
            >批准</el-button
          >
          <el-button v-if="canReject" @click="btnFlow('reject')"
            >驳回</el-button
          >
          <el-button v-if="canRefuse" @click="btnFlow('refuse')"
            >拒绝</el-button
          >
          <el-button v-if="canSalesReview" @click="salesReview">销审</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <basic-information
              :info="basicInfo.info"
              :label-width="basicInfo.labelWidth"
            >
              <template v-slot:basic-fileUrlList>
                <EleGallery
                  v-if="basicInfo.info.data.fileUrlList"
                  :lazy="true"
                  :size="150"
                  :source="basicInfo.info.data.fileUrlList"
                  title="附件"
                />
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :check-box="true"
                :tab-index="true"
                :is-row-click-select="true"
                @handleEvent="handleEvent"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <adjust-price-modify
      v-if="adjustPriceModifyInfo.visible"
      v-model:visible="adjustPriceModifyInfo.visible"
      :table-row="adjustPriceModifyInfo.tableRow"
      :title="adjustPriceModifyInfo.title"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="adjustPriceDetail">
import EleGallery from '@/components/UploadImgNew/eleGallery'
const AdjustPriceModify = defineAsyncComponent(() => import('./modify'))
const UploadList = defineAsyncComponent(() =>
  import('@/components/UploadVideo/uploadList')
)
import {
  getAdjustPriceOrderDetailsAll,
  submitAdjustPriceOrder,
  approveAdjustPriceOrder,
  rejectAdjustPriceOrder,
  refuseAdjustPriceOrder,
  recallAdjustPriceOrder,
  salesReviewAdjustPriceOrder,
  getAdjustPriceOrder,
} from '@/api/purch'
import { orderOpAffairAll } from '@/api/affair'
import axios from 'axios'
import { getCustomizeSetting } from '@/api/customize'
import { ElMessage, ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'tableRow', 'id'])

const basicInfo = reactive({
  info: {
    data: {},
    fieldList: [
      { label: '单号', value: 'orderNo' },
      { label: '供应商', value: 'supplierName', type: 'text' },
      { label: '生效日期', value: 'effectiveDate', type: 'text' },
      { label: '状态', value: 'statusValue' },
      { label: '创建人', value: 'createUserName' },
      { label: '批准人', value: 'confirmUserName' },
      { label: '备注', value: 'remark', type: 'popover' },
      {
        label: '附件',
        value: 'fileUrlList',
        type: 'slot',
        className: 'not-br',
      },
    ],
  },
  labelWidth: '130px',
})
const fullInfo = reactive({
  btnList: [{ value: 'button', type: 'slot' }],
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 113,
    orderId: props.id || props.tableRow.id,
    sort: 'operate_time desc',
  },
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
})
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      adjustPriceId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.tableRow.id,
      },
    },
    queryParams: {},
  },
})
const adjustPriceModifyInfo = reactive({
  visible: false,
  title: '',
  tableRow: {},
})
const action = ref(axios.defaults.baseURL + '/pub/uploadfile')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('adjustPrice:submit') &&
    (basicInfo.info.data.status === 1 || basicInfo.info.data.status === 4) &&
    !basicInfo.info.data.platOrderNo
  )
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('adjustPrice:update') &&
    (basicInfo.info.data.status === 1 || basicInfo.info.data.status === 4) &&
    !basicInfo.info.data.platOrderNo
  )
})
const canApprove = computed(() => {
  return (
    proxy.$permission('adjustPrice:approve') &&
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type == 1 &&
    basicInfo.info.data.status === 2
  )
})
const canReject = computed(() => {
  return (
    proxy.$permission('adjustPrice:reject') &&
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type == 1 &&
    basicInfo.info.data.status === 2
  )
})
const canRefuse = computed(() => {
  return (
    proxy.$permission('adjustPrice:refuse') &&
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type == 1 &&
    basicInfo.info.data.status === 2
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('adjustPrice:recall') &&
    (basicInfo.info.data.status === 2 ||
      (basicInfo.info.data.status === 6 &&
        proxy.$store.state.permission.systemConfig
          .adjust_price_order_approval_type == 0)) &&
    !basicInfo.info.data.platOrderNo
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('adjustPrice:salesReview') &&
    proxy.$store.state.permission.systemConfig
      .adjust_price_order_approval_type != 0 &&
    basicInfo.info.data.status === 6
  )
})

onMounted(() => {
  setData()
})

function setData() {
  let obj = {}
  tableInfo.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
function returnBack() {
  emit('returnBack', false)
}
function update() {
  adjustPriceModifyInfo.title = '修改调价单'
  adjustPriceModifyInfo.tableRow = { ...basicInfo.info.data }
  adjustPriceModifyInfo.visible = true
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'adjustOrder',
    orderIds: [props.id || props.tableRow.id],
  }
  submitAdjustPriceOrder(data).then((resp) => {
    if (resp && resp.success) {
      getMain()
      getList()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(code) {
  const row = basicInfo.info.data
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = approveAdjustPriceOrder
    const data = {
      orderId: row.id,
    }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getMain()
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAdjustPriceOrder
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAdjustPriceOrder
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getMain()
          getList()
        }
      })
    })
}
// 撤回
function recall() {
  recallAdjustPriceOrder([basicInfo.info.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 销审
function salesReview() {
  salesReviewAdjustPriceOrder([basicInfo.info.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      getMain()
      getList()
      ElMessage.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      ElMessage.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 获取列表
function getList() {
  getAdjustPriceOrderDetailsAll(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function getMain() {
  getAdjustPriceOrder(props.id || props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      basicInfo.info.data = resp.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'AdjustPriceOrderDetail-com.slip.spd.entity.vo.purch.AdjustPriceOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(tableInfo.fieldList, data.detail, true)
      tableInfo.fieldList = obj.fieldList
      getMain()
      getList()
    }
  })
}
function returnModify() {
  getCustomize()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
</script>

<style scoped></style>
